//
//  LockScreenView.m
//  iMoney
//
//  Created by Sean McGrail on 3/4/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LockScreenView.h"
#import "SFHFKeychainUtils.h"


@implementation LockScreenView


@synthesize delegate;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
    }
    return self;
}


-(void) setUpPassword
{
	NSError* error;
	
	#if TARGET_IPHONE_SIMULATOR
		//mainPassword = [[SFHFKeychainUtils getPasswordForUsername:[[UIDevice currentDevice] name] andServiceName:@"lockScreen" error:&error] retain];	
		mainPassword= @"1234";
	#else
		mainPassword = [[SFHFKeychainUtils getPassword:[[UIDevice currentDevice] name] error:&error] retain];
	#endif
	
	if(mainPassword == nil)
	{
		UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"No Password Set" message:@"Please input new password" delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
		// optional - add more buttons:
		[alert addButtonWithTitle:@"OK"];
		[alert show];
		
		passwordSet= NO;
		
	}
	else
	{
		passwordSet=YES;
	}
	
}



-(void) createMainLockView:(UIImageView*)backgroundImage
{
	//[self setBackgroundColor:[UIColor whiteColor]];
	
	UIView* bImage=nil;
	if(backgroundImage == nil){
		bImage= [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
		bImage.backgroundColor = [UIColor groupTableViewBackgroundColor];
	}
	else
	{
		bImage = [backgroundImage autorelease];
	}
	
	const NSInteger XLOC = 20;
	const NSInteger YLOC = 100;
	const NSInteger WIDTH = 60;
	const NSInteger HEIGHT = 60;
	const NSInteger TEXT_WIDTH = 300;
	
	UILabel *name = [[UILabel alloc ] initWithFrame:CGRectMake(70 , 20, TEXT_WIDTH, 40)];
	name.textAlignment =  UITextAlignmentLeft;
	name.textColor = [UIColor whiteColor];
	name.backgroundColor = [UIColor clearColor];
	name.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(20.0)];
	name.text = @"Input Password:";
	
	
	first = [[UITextField alloc] initWithFrame:CGRectMake(XLOC, YLOC, WIDTH, HEIGHT)];
	first.delegate = self;
	first.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:(28.0)];
	first.borderStyle =  UITextBorderStyleLine;
	[first setBackgroundColor:[UIColor whiteColor]];
	first.keyboardType = UIKeyboardTypeNumberPad;
	first.enablesReturnKeyAutomatically = YES;
	first.secureTextEntry= YES;
	first.textAlignment= UITextAlignmentCenter;
	first.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
	[first addTarget:self action:@selector(characterEntered:) forControlEvents:UIControlEventEditingChanged];

	
	second = [[UITextField alloc] initWithFrame:CGRectMake(XLOC+70, YLOC, WIDTH, HEIGHT)];
	second.delegate = self;
	second.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:(28.0)];
	second.adjustsFontSizeToFitWidth= YES;
	second.borderStyle =  UITextBorderStyleLine;
	[second setBackgroundColor:[UIColor whiteColor]];
	second.keyboardType = UIKeyboardTypeNumberPad;
	second.enablesReturnKeyAutomatically = YES;
	second.secureTextEntry= YES;
	second.textAlignment= UITextAlignmentCenter;
	second.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
	[second addTarget:self action:@selector(characterEntered:) forControlEvents:UIControlEventEditingChanged];
	
	third = [[UITextField alloc] initWithFrame:CGRectMake(XLOC+140, YLOC, WIDTH, HEIGHT)];
	third.delegate = self;
	third.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:(28.0)];
	third.adjustsFontSizeToFitWidth= YES;
	third.borderStyle =  UITextBorderStyleLine;
	[third setBackgroundColor:[UIColor whiteColor]];
	third.keyboardType = UIKeyboardTypeNumberPad;
	third.enablesReturnKeyAutomatically = YES;
	third.secureTextEntry= YES;
	third.textAlignment= UITextAlignmentCenter;
	third.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
	[third addTarget:self action:@selector(characterEntered:) forControlEvents:UIControlEventEditingChanged];
	
	fourth = [[UITextField alloc] initWithFrame:CGRectMake(XLOC+210, YLOC, WIDTH, HEIGHT)];
	fourth.delegate = self;
	fourth.font= [UIFont fontWithName:@"Arial Rounded MT Bold" size:(28.0)];
	fourth.adjustsFontSizeToFitWidth= YES;
	fourth.borderStyle =  UITextBorderStyleLine;
	[fourth setBackgroundColor:[UIColor whiteColor]];
	fourth.keyboardType = UIKeyboardTypeNumberPad;
	fourth.enablesReturnKeyAutomatically = YES;
	fourth.secureTextEntry= YES;
	fourth.textAlignment= UITextAlignmentCenter;
	fourth.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
	[fourth addTarget:self action:@selector(characterEntered:) forControlEvents:UIControlEventEditingChanged];
	
	[self addSubview:bImage];
	[self addSubview:name];
	[name release];
	[self addSubview:first];
	[self addSubview:second];
	[self addSubview:third];
	[self addSubview:fourth];
	
	[first becomeFirstResponder];

}


-(id)initLockScreen:(id<LockScreenInputDoneDelegate>) adelegate:(UIImageView*) backgroundImage
{
	
	[self initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	
	self.delegate = adelegate;
	
	[self setUpPassword];
	[self createMainLockView:backgroundImage];
	
	return self;
}

-(id)initLockScreen:(id<LockScreenInputDoneDelegate>) adelegate
{
	return [self initLockScreen:nil];
}


-(NSString*) getPasswordFromInputs
{
	NSString* pass = first.text;
	
	return [[[pass stringByAppendingString:second.text] stringByAppendingString:third.text] stringByAppendingString:fourth.text];
}

-(void) resetToFirstInput
{
	first.text = @"";
	second.text = @"";
	third.text = @"";
	fourth.text = @"";
	[first becomeFirstResponder];	
}

-(void) validatedCorrectly
{
	[fourth resignFirstResponder];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[self.delegate inputSucceded];	
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(alertView == checkFirstTime)
	{
		if(buttonIndex == 0)
		{
			
			NSError* error=nil;
		#if TARGET_IPHONE_SIMULATOR
			//[SFHFKeychainUtils storeUsername:[[UIDevice currentDevice] name] andPassword:[self getPasswordFromInputs] forServiceName:@"lockScreen" updateExisting:YES error:&error];
		#else
			[SFHFKeychainUtils createPassword:[self getPasswordFromInputs] forIdentifier:[[UIDevice currentDevice] name] error:&error];
		#endif
			
			[self validatedCorrectly];
		}
		else if(buttonIndex == 1)
			[self resetToFirstInput];
		
	}
	else if(alertView == checkInput)
	{
		[self resetToFirstInput];
	}
}


//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//	
//	
//}



-(void) checkAndValidatePassword
{
	if(!passwordSet)
	{
		checkFirstTime = [[[UIAlertView alloc] initWithTitle:[[self getPasswordFromInputs] stringByAppendingString:@" Will be the set password"] message:@"Do You want to keep this?"
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil] autorelease];
		[checkFirstTime show];
	}
	else {
		
		if(![[self getPasswordFromInputs] compare:mainPassword] == NSOrderedSame)
		{
			checkInput = [[[UIAlertView alloc] initWithTitle:@"Password not correct" message:@""
															delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
			[checkInput addButtonWithTitle:@"Ok"];
			[checkInput show];
			
		}
		else {
			[self validatedCorrectly];
		}

	}

	
	
}


- (void)characterEntered:(id)sender {
	
	if (sender == first) 
	{
		if (first.text && [first.text length] == 1) 
		{
			[second becomeFirstResponder];
		}
	} 
	else if (sender == second) 
	{
		if (second.text && [second.text length] == 1) 
		{
			[third becomeFirstResponder];
		}
	}
	else if (sender == third) 
	{
		if (third.text && [third.text length] == 1) 
		{
			[fourth becomeFirstResponder];
		}
	}
	else if (sender == fourth) 
	{
		if (fourth.text && [fourth.text length] == 1) 
		{
			[self checkAndValidatePassword];
			
		}
	}
	
	
}

-(void) backButton:(id)sender
{
	UITextField* currentText;
	for (UIView *subView in self.subviews) {
		
		if([subView isKindOfClass:[UITextField class]] )
		{
			if([((UITextField*)subView) isFirstResponder])
			{
				currentText = ((UITextField*)subView);
			}
		}
		
	}
	
	if(currentText == second)
	{
		first.text = @"";
		second.text = @"";
		[first becomeFirstResponder];
	}
	else if(currentText == third)
	{
		second.text = @"";
		third.text = @"";
		[second becomeFirstResponder];
	}
	else if(currentText == fourth)
	{
		third.text = @"";
		fourth.text = @"";
		[third becomeFirstResponder];
	}
	

}





- (void)keyboardWillShow:(NSNotification *)note {  
    // create custom butto
	UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
	backButton.frame = CGRectMake(215, 165, 106, 53);
	backButton.adjustsImageWhenHighlighted = NO;
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateHighlighted];
	[backButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
	
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
            [keyboard addSubview:backButton];
    }
}






- (void)drawRect:(CGRect)rect {
}


- (void)dealloc {
	
	
	if(checkFirstTime != nil)
	[checkFirstTime release];
	if(checkInput != nil)
	[checkInput release];
	[mainPassword release];
    [super dealloc];
}


@end
